package com.tools.developer.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.WindowManager;

public class Env {
	private static double screenSize = 0;
	private static final String TOOLS_USER_ID = "Tools_User_Id";

	public static String getVersionName(Context context) {
		if (context == null)
			return null;

		ComponentName cn = new ComponentName(context, context.getClass());
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					cn.getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			return null;
		}
	}

	public static String getVersionNameCode(Context context) {
		if (context == null)
			return null;

		ComponentName cn = new ComponentName(context, context.getClass());
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					cn.getPackageName(), 0);

			return info.versionName + "(" + info.versionCode + ")";
		} catch (NameNotFoundException e) {
			return null;
		}
	}

	public static int getVersionCode(Context context) {
		if (context == null)
			return -1;
		ComponentName cn = new ComponentName(context, context.getClass());
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					cn.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			return -1;
		}
	}

	// 判断网络是否存在
	public static boolean IsNetworkAvailable(Context context) {
		if (context != null) {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (cm != null) {
				// NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
				// for (NetworkInfo info : networkInfos) {
				// if (info.getState() == NetworkInfo.State.CONNECTED)
				// return true;
				// }
				if (cm.getActiveNetworkInfo() != null) {
					if (cm.getActiveNetworkInfo().isAvailable()) {
						return true;
					}
				}
			}
			return false;
		}
		return false;
	}

	public static boolean IsWifiNetworkAvailable(Context context) {
		if (context == null)
			return false;

		ConnectivityManager conmgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		State wifi = conmgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (wifi == State.CONNECTED)
			return true;
		return false;
	}

	public static int getNetworkType(Context cx) {
		ConnectivityManager connectivityManager = (ConnectivityManager) cx
				.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();// 获取网络的连接情况
		return activeNetInfo.getType();
	}

	public static String getIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	public static int getSoftwareVersionCode(Context context) {
		if (context == null)
			return -1;
		ComponentName cn = new ComponentName(context, context.getClass());
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					cn.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			return -1;
		}
	}

	public static boolean IsGPRSNetworkAvailable(Context context) {
		if (context == null)
			return false;

		ConnectivityManager conmgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		State mobile = null;
		if (conmgr != null) {
			NetworkInfo net = conmgr
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (net != null) {
				mobile = net.getState();
			}
		}
		if (mobile != null && mobile == State.CONNECTED)
			return true;
		return false;
	}

	/**
	 * 如果有SD卡， 则存储在sd卡中，如果没有sd卡，则存在packagename下
	 * 
	 * @param context
	 * @return
	 */
	public static String getPath(Context context) {
		String kbdPath;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			kbdPath = Constant.TOOLS_LOG_PATH;
		} else {
			kbdPath = Asset.getAbsDbFileDirPath(context) + "/";
		}

		return kbdPath;
	}

	public static boolean isSdcardExist() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean IsCanWrite() {
		String state = android.os.Environment.getExternalStorageState();
		if (android.os.Environment.MEDIA_MOUNTED.equals(state)) {
			if (android.os.Environment.getExternalStorageDirectory().canWrite()) {
				return true;
			}
		}

		return false;
	}

	private static final String SCHEME = "package";
	/**
	 * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.1及之前版本)
	 */
	private static final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";
	/**
	 * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.2)
	 */
	private static final String APP_PKG_NAME_22 = "pkg";

	private static final String ACTION_APPLICATION_DETAILS_SETTINGS_23 = "android.settings.APPLICATION_DETAILS_SETTINGS";
	/**
	 * InstalledAppDetails所在包名
	 */
	private static final String APP_DETAILS_PACKAGE_NAME = "com.android.settings";
	/**
	 * InstalledAppDetails类名
	 */
	private static final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";

	/**
	 * 调用系统InstalledAppDetails界面显示已安装应用程序的详细信息。 对于Android 2.3（Api Level
	 * 9）以上，使用SDK提供的接口； 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）。
	 * 
	 * @param packageName
	 *            应用程序的包名
	 */
	public static Intent getPackageDetailsIntent(String packageName) {
		Intent intent = new Intent();
		int apiLevel = 0;
		try {
			apiLevel = VERSION.SDK_INT;
		} catch (Exception ex) {
		}
		if (apiLevel >= 9) { // 2.3（ApiLevel 9）以上，使用SDK提供的接口
			intent.setAction(ACTION_APPLICATION_DETAILS_SETTINGS_23);
			Uri uri = Uri.fromParts(SCHEME, packageName, null);
			intent.setData(uri);
		} else { // 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）
			// 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
			final String appPkgName = (apiLevel > 7 ? APP_PKG_NAME_22
					: APP_PKG_NAME_21);
			intent.setAction(Intent.ACTION_VIEW);
			intent.setClassName(APP_DETAILS_PACKAGE_NAME,
					APP_DETAILS_CLASS_NAME);
			intent.putExtra(appPkgName, packageName);
		}
		return intent;
	}

	public static int getSDKVersion() {
		return android.os.Build.VERSION.SDK_INT;
	}

	/**
	 * 得到屏幕尺寸，单位，英寸
	 * 
	 * @param activity
	 * @return 尺寸大于6时为平板
	 */
	public static double getScreenSizeIn(Context context) {
		if (screenSize != 0) {
			return screenSize;
		}
		DisplayMetrics dm = new DisplayMetrics();

		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);

		windowManager.getDefaultDisplay().getMetrics(dm);
		// 得到屏幕的宽(像素)
		int screenX = dm.widthPixels;
		// 得到屏幕的高(像素)
		int screenY = dm.heightPixels;
		// 每英寸的像素点
		int dpi = dm.densityDpi;
		// 得到屏幕的宽(英寸)
		float a = screenX / dpi;
		// 得到屏幕的高(英寸)
		float b = screenY / dpi;
		// 勾股定理
		screenSize = FloatMath.sqrt((a * a) + (b * b));
		return screenSize;
	}

	/**
	 * 获取屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics metric = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(metric);
		return metric.widthPixels;
	}

	public static boolean checkApkInstall(Context context, String packageName) {
		if (TextUtils.isEmpty(packageName) || context == null)
			return false;
		try {
			context.getPackageManager().getApplicationInfo(packageName,
					PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		} catch (NameNotFoundException e) {
			return false;
		}
	}

	/**
	 * 在MAIN_TAB,只需要检测更新与否，不保存配置文件； 在BOUTIQUE_TAB时需要写配置文件。
	 * 
	 * @param c
	 * @param api_url
	 * @param count
	 * @param flag
	 * @param where
	 * @return
	 */
	public static boolean isModifiedForServer(Context c, String api_url,
			int count, int flag, int where) {

		if (Env.IsNetworkAvailable(c.getApplicationContext())) {
			try {
				HttpClient httpclient = new DefaultHttpClient();
				httpclient.getParams().setParameter(
						CoreConnectionPNames.SO_TIMEOUT, 6000);
				HttpGet httpget = new HttpGet(api_url);
				HttpResponse response = httpclient.execute(httpget);
				if (response.getStatusLine().getStatusCode() != 200) {
					return true;
				}
				Header[] header = response.getHeaders("ETag");
				String etag = SharedPrefHelper
						.getEtag(c, count + "", flag + "");
				if ("".equals(etag)) {
					if (where == Constant.BOUTIQUE_TAB) {
						SharedPrefHelper.putEtag(c, count + "", flag + "",
								header[0].toString());
					}
					return true;
				} else if (!etag.equals(header[0].toString())) {
					if (where == Constant.BOUTIQUE_TAB) {
						SharedPrefHelper.putEtag(c, count + "", flag + "",
								header[0].toString());
					}
					return true;
				}
			} catch (Exception e) {
				return false;
			}
		} else {
			return false;
		}
		return false;
	}

	public static boolean isTimeout() {
		try {
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			Date timeoutDate = format.parse("2012-11-14 24:00:00");
			if (date.before(timeoutDate)) {
				return false;
			} else {
				return true;
			}
		} catch (ParseException e) {
			return true;
		}
	}

	/**
	 * need permission: android.permission.WRITE_SETTINGS
	 * 
	 * @param context
	 * @param userId
	 */
	public static void writeUserid(Context context, String userId) {
		Settings.System.putString(context.getContentResolver(), TOOLS_USER_ID,
				userId);
	}

	public static String readUserId(Context context) {
		String userId = Settings.System.getString(context.getContentResolver(),
				TOOLS_USER_ID);
		if (TextUtils.isEmpty(userId)) {
			// TODO 生成UserId
		}
		return userId;
	}
	
	public static String getLocalIpAddress() {
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			if (en != null) {
				while (en.hasMoreElements()) {
					NetworkInterface intf = en.nextElement();
					Enumeration<InetAddress> enumIpAddr = intf
							.getInetAddresses();
					if (enumIpAddr != null) {
						while (enumIpAddr.hasMoreElements()) {
							InetAddress inetAddress = enumIpAddr.nextElement();
							if (!inetAddress.isLoopbackAddress()) {
								String ip = inetAddress.getHostAddress()
										.toString();
								return filterIpForUrl(ip);
							}
						}
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("getLocalIpAddress:", ex.toString());
		}
		return null;
	}

	/**
	 * 过滤ip中的网卡名字
	 * 
	 * @param ip
	 * @return
	 */
	public static String filterIpForUrl(String ip) {
		if (!TextUtils.isEmpty(ip)) {
			if (KLog.DEG) {
				KLog.i("local ip:" + ip);
			}
			ip = ip.substring(0, ip.indexOf("%"));
			if (KLog.DEG) {
				KLog.i("local filtered ip:" + ip);
			}
		}
		return ip;
	}
}
